package com.s7.ui.app;

import android.os.Bundle;
import android.view.animation.AlphaAnimation;
import android.view.animation.Animation;
import android.widget.LinearLayout;

import com.s7.ui.R;
import com.s7.ui.arch.ArchActivity;
import com.s7.ui.util.ViewUtils;

/**
 * 基础启动页
 */
public abstract class BaseSplashActivity extends ArchActivity {

    /**
     * 默认启动页过渡时间
     */
    private static final int DEFAULT_DURATION_MILLIS = 1000;

    // 启动页视图
    protected LinearLayout mWelcome;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_base_splash);
        mWelcome = findViewById(R.id.base_splash_welcome);
        initSplashView(getSplashImgResId());
        onCreateActivity();
    }

    /**
     * 初始化启动界面
     * @param resId 背景资源图片资源ID
     */
    protected void initSplashView(int resId) {
        if (resId != 0) {
            ViewUtils.setBackground(this, mWelcome, resId);
            startSplash(true);
        }
    }

    /**
     * 初始化启动界面背景图片
     * @return 背景图片资源ID
     */
    protected int getSplashImgResId() {
        return 0;
    }

    /**
     * activity启动后的初始化
     */
    protected abstract void onCreateActivity();

    /**
     * 启动页结束后的动作
     */
    protected abstract void onSplashFinished();

    /**
     * @return 启动页持续的时间
     */
    protected long getDurationMillis() {
        return DEFAULT_DURATION_MILLIS;
    }

    /**
     * 开启过渡
     * @param enableAlphaAnim 是否启用渐近动画
     */
    protected void startSplash(boolean enableAlphaAnim) {
        if (enableAlphaAnim) {
            startSplashAnim(new AlphaAnimation(0.1F, 1.0F));
        } else {
            startSplashAnim(new AlphaAnimation(1.0F, 1.0F));
        }
    }

    /**
     * 开启引导过渡动画
     * @param anim
     */
    private void startSplashAnim(Animation anim) {
        ViewUtils.checkNull(anim, "Splash Animation can not be null");
        anim.setDuration(getDurationMillis());
        anim.setAnimationListener(new Animation.AnimationListener() {
            @Override
            public void onAnimationStart(Animation animation) {
            }

            @Override
            public void onAnimationRepeat(Animation animation) {
            }

            @Override
            public void onAnimationEnd(Animation animation) {
                onSplashFinished();
            }
        });
        mWelcome.startAnimation(anim);
    }

    @Override
    protected void onDestroy() {
        ViewUtils.recycleBackground(mWelcome);
        super.onDestroy();
    }

}
